package cn.hexcloud.dga.governance.assessor.calc;

import cn.hexcloud.dga.common.util.SqlParser;
import cn.hexcloud.dga.governance.assessor.Assessor;
import cn.hexcloud.dga.governance.bean.AssessParam;
import cn.hexcloud.dga.governance.bean.GovernanceAssessDetail;
import lombok.Getter;
import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Stack;

@Component("SELECT_ALL")
public class SelectAllAssessor extends Assessor {
    @Override
    public void checkProblem(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) throws Exception {
        if (assessParam.getTableMetaInfo().getTableMetaInfoExtra().getDwLevel().equals("ODS") || assessParam.getTDsTaskDefinition() == null) {
            return;
        }
        String sql = assessParam.getTDsTaskDefinition().getSql();
        if (sql == null) {
            return;
        }

        SelectAllDispatcher selectAllDispatcher = new SelectAllDispatcher();
        SqlParser.sqlParse(sql, selectAllDispatcher);

        if (selectAllDispatcher.hasSelectAll) {
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            governanceAssessDetail.setAssessProblem("存在select * 语句" + " >> " + sql);
        }
    }

    public class SelectAllDispatcher implements Dispatcher {

        @Getter
        boolean hasSelectAll = false;

        @Override
        public Object dispatch(Node nd, Stack<Node> stack, Object... nodeOutputs) throws SemanticException {
            ASTNode queryNode = (ASTNode) nd;
            if (queryNode.getType() == HiveParser.TOK_ALLCOLREF) {
                hasSelectAll = true;
            }
            return null;
        }
    }
}
